<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Core\Common\Handler;

use Core\Common\Base\Log;
use Core\Common\Base\Service;

/**
 * 定时发现consul上注册的服务
 *
 * @author baiyang@ibantang.com
 */
class ServiceHandler
{
    private static $time = 0;

    public static function run()
    {
        $rnd = rand(10, 19);
        if (time() - self::$time < $rnd) {
            usleep(100000);
            return;
        }

        $data = Service::getHealthServices();
        if (empty($data)) {
            usleep(100000);
            return;
        }

        $error = $data["error"] ?? "";
        if (!empty($error)) {
            Log::coreLog([$error, "in service handler"]);
            usleep(100000);
            return;
        }

        $ret = $data["data"] ?? [];
        if (empty($ret)) {
            usleep(100000);
            return;
        }

        self::$time = time();
        $count = 0;
        foreach ($ret as $k => $v) {
            if (empty($v)) {
                continue;
            }
            $count++;
            Service::setService($k, $v, self::$time);
        }
        Log::coreLog(["in ServiceHandler, found {$count} service, time "]);
        return $ret;
    }
}
